package com.ruoyi.pcwl.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.pcwl.domain.Article;
import com.ruoyi.pcwl.domain.ArticleChannel;
import com.ruoyi.pcwl.domain.ArticleContent;
import com.ruoyi.pcwl.mapper.ArticleContentMapper;
import com.ruoyi.pcwl.mapper.ArticleMapper;
import com.ruoyi.pcwl.service.IArticleContentService;
import com.ruoyi.pcwl.service.IArticleService;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpFreePublishService;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.freepublish.WxMpFreePublishArticles;
import me.chanjar.weixin.mp.bean.freepublish.WxMpFreePublishInfo;
import me.chanjar.weixin.mp.bean.freepublish.WxMpFreePublishItem;
import me.chanjar.weixin.mp.bean.freepublish.WxMpFreePublishList;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;


/**
 * 文章信息，存储已发布的文章Service业务层处理
 *
 * @author ruoyi
 * @date 2024-01-11
 */
@Service
public class ArticleServiceImpl extends ServiceImpl<ArticleMapper, Article> implements IArticleService
{
    @Autowired
    private ArticleMapper articleMapper;

    @Autowired
    private IArticleContentService articleContentService;

    @Resource
    ArticleContentMapper articleContentMapper;

    @Autowired
    WxMpService wxMpService;

    /**
     * 发布文章到小程序
     *
     * @return
     */
    @Override
    public void publishArticle(String id) {
        Article article = articleMapper.selectArticleById(id);
        if (article==null) {
            return;
        }
        if (article.getSyncStatus()==1)
            article.setSyncStatus(0);
        else
            article.setSyncStatus(1);
        article.setPublishTime(new Date());

            articleMapper.updateById(article);

    }

    /**
     * 分页获取已发布的文章
     *
     * @return 文章信息，存储已发布的文章
     */
    @Override
    public IPage<Article> getPublishArticle(Page<Article> articlePage, Article article) {
        QueryWrapper<Article> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("sync_status","1");
        queryWrapper.orderByDesc("publish_time");
        baseMapper.selectList(queryWrapper);


        return baseMapper.selectPage(articlePage,queryWrapper);
    }

    /**
     * 根据Id获取对象
     */
    @Override
    public Article getArticleById(Long id) {
        return baseMapper.selectById(id);
    }

    /**
     * 查询文章信息，存储已发布的文章
     *
     * @return 文章信息，存储已发布的文章
     */
    @Override
    public void syncWechatArticle() throws WxErrorException {

        WxMpFreePublishService freePublishService = wxMpService.getFreePublishService();
        WxMpFreePublishList publicationRecords = freePublishService.getPublicationRecords(0, 90,0);

        //从数据库中取出最近的100篇文章
        QueryWrapper<Article> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("created_time");
        queryWrapper.last("limit 100");
        List<Article> articles = baseMapper.selectList(queryWrapper);

        //取出本地库中的已同步文章id
        List<String> articleIdCollect = articles.stream().map(item -> item.getArticleId()).collect(Collectors.toList());


        Article article = null;
        ArticleContent articleContent = null;
        ArrayList<Article> articleList = new ArrayList<>();
        ArrayList<ArticleContent> articleContentList = new ArrayList<>();
        List<WxMpFreePublishItem> items = publicationRecords.getItems();
        for (WxMpFreePublishItem item : items) {

           if (!articleIdCollect.contains(item.getArticleId())) {
               article= new Article();
               articleContent = new ArticleContent();
               article.setArticleId(item.getArticleId());
               articleContent.setArticleId(item.getArticleId());
               //取出返回值中的content里面包含的文章信息
               WxMpFreePublishInfo content = item.getContent();
               List<WxMpFreePublishArticles> newsItem = content.getNewsItem();
               for (WxMpFreePublishArticles wxMpFreePublishArticles : newsItem) {
                   article.setAuthorName(wxMpFreePublishArticles.getAuthor());
                   article.setImages(wxMpFreePublishArticles.getThumbUrl());
                   article.setStaticUrl(wxMpFreePublishArticles.getUrl());
                   article.setTitle(wxMpFreePublishArticles.getTitle());
                   articleContent.setContent(wxMpFreePublishArticles.getContent());
               }
               article.setCreatedTime(new Date(Long.parseLong(item.getUpdateTime())*1000));
           }
           if (article!=null) {
               articleList.add(article);
               article = null;
           }
           if (articleContent!=null) {
               articleContentList.add(articleContent);
                articleContent = null;
           }
        }
        if (CollectionUtils.isEmpty(articleList)||CollectionUtils.isEmpty(articleContentList)) {
            return;
        }
        saveOrUpdateBatch(articleList);
        articleContentService.saveOrUpdateBatch(articleContentList);

    }

    /**
     * 查询文章信息，存储已发布的文章
     *
     * @param id 文章信息，存储已发布的文章主键
     * @return 文章信息，存储已发布的文章
     */
    @Override
    public Article selectArticleById(String id)
    {
        return articleMapper.selectArticleById(id);
    }

    /**
     * 查询文章信息，存储已发布的文章列表
     *
     * @param article 文章信息，存储已发布的文章
     * @return 文章信息，存储已发布的文章
     */
    @Override
    public List<Article> selectArticleList(Article article)
    {
        return articleMapper.selectArticleList(article);
    }

    /**
     * 新增文章信息，存储已发布的文章
     *
     * @param article 文章信息，存储已发布的文章
     * @return 结果
     */
    @Override
    public int insertArticle(Article article)
    {
        return articleMapper.insertArticle(article);
    }

    /**
     * 修改文章信息，存储已发布的文章
     *
     * @param article 文章信息，存储已发布的文章
     * @return 结果
     */
    @Override
    public int updateArticle(Article article)
    {
        article.setUpdateTime(new Date());
        return baseMapper.updateById(article);
    }


    /**
     * 批量删除文章信息，存储已发布的文章
     *
     * @param ids 需要删除的文章信息，存储已发布的文章主键
     * @return 结果
     */
    @Override
    public int deleteArticleByIds(String[] ids)
    {
        for (String id : ids) {
            Article article = baseMapper.selectById(id);
            articleContentMapper.delete(new QueryWrapper<ArticleContent>().eq("article_id",article.getArticleId()));
        }

        return articleMapper.deleteArticleByIds(ids);
    }

    /**
     * 删除文章信息，存储已发布的文章信息
     *
     * @param id 文章信息，存储已发布的文章主键
     * @return 结果
     */
    @Override
    public int deleteArticleById(String id)
    {
        return articleMapper.deleteArticleById(id);
    }
}
